<template>
  <div class="awsCenter">
    <div style="border: black 0px solid;width: 100%;height: 780px;display: flex;
flex-direction: column;
align-items: center;">
      <!--    按钮栏    -->
      <div class="awsCenter" style="width: 100%;height: 40px;border: black 0px solid">
        <el-button style="width: 80px;margin-left: auto" type="primary" @click="showRoom=true;sou=false;dialogTitle='新增咨询室'">新增</el-button>
        <el-button @click="delAll">批量删除</el-button>

      </div>


      <!--   表格    -->
      <el-table  :data="tableData" stripe style="width: 100%;margin-top: 20px" @selection-change="selectRoom" height="700px" :row-style="{ height: '80px' }">
        <el-table-column type="selection" width="55" />

        <el-table-column prop="room" label="咨询室名称" width="150px"/>
        <el-table-column prop="capacity" label="容纳人数" width="120px"/>
        <el-table-column prop="location" label="地点" width="200px"/>
        <el-table-column prop="timetotal" label="已安排时间段" width="180">
          <template #default="scope">
            <el-tag type="info">{{backText(scope.row)}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="时间信息" width="400px">
          <template #default="{ row }">
            <el-button link type="primary" @click="showTimes(row)">点击查看</el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button type="primary" plain :icon="Edit" circle @click="dialogTitle='修改咨询室';showRoom=true;update(row);sou=true" />
            <el-button type="danger" plain :icon="Delete" circle @click="showConfirmDialog(row)" />
          </template>
        </el-table-column>
      </el-table>


      <el-dialog
        @close="cleanForm"
        v-model="showRoom"
        :title="dialogTitle"
        width="800"
        align-center
        :close-on-click-modal="false"
      >
        <div style="padding: 20px;height: 400px">
          <el-form :model="roomForm" label-position="top" label-width="100px">

            <el-tabs v-model="roomClass" >
              <el-tab-pane label="咨询室" name="room">
                <el-form-item prop="room" label-position="top" label="咨询室名称">
                  <el-input style="width: 200px" v-model="roomForm.room" ></el-input>
                </el-form-item>
                <el-form-item prop="capacity" label-position="top" label="容纳人数" >
                  <el-input-number v-model="roomForm.capacity" :min="2" :max="5" />
                </el-form-item>
                <el-form-item prop="location" label-position="top" label="地点">
                  <el-input
                    v-model="roomForm.location"
                    style="width: 240px"
                    :rows="2"
                    type="textarea"
                    placeholder="请输入地点"

                  />
                </el-form-item>
              </el-tab-pane>
              <el-tab-pane label="时间段" name="times">
                <div style="width: 100%;display: flex">
                  <el-button style="margin-left: auto" @click="addRow" plain type="primary">增行</el-button>
                </div>
                <el-table :data="rows" style="width: 100%;height: 270px;overflow-y: auto;">
                  <el-table-column label="开始时间">
                    <template v-slot="{ row }">
                      <el-time-picker v-model="row.startTime" placeholder="选择开始时间" style="width: 100%" />
                    </template>
                  </el-table-column>
                  <el-table-column label="结束时间">
                    <template v-slot="{ row }">
                      <el-time-picker  v-model="row.endTime" placeholder="选择结束时间" style="width: 100%" />
                    </template>
                  </el-table-column>
                  <el-table-column label="启用状态">
                    <template v-slot="{ row }">
                      <el-switch v-model="row.isAvailable" active-text="启用" inactive-text="停用" active-value="1" inactive-value="0" />
                    </template>
                  </el-table-column>
                  <el-table-column label="操作">
                    <template v-slot="{ row, $index }">
                      <el-button  type="danger" circle plain :icon="Delete" @click="deleteRow($index)"></el-button>
                    </template>
                  </el-table-column>
                </el-table>

              </el-tab-pane>

            </el-tabs>

          </el-form>
        </div>

        <template #footer>
          <div style="margin-top: -20px">
            <el-button @click="showRoom = false">取 消</el-button>
            <el-button type="primary" @click="saveOrUpdate">
              确 认
            </el-button>
          </div>
        </template>

      </el-dialog>


      <el-dialog
        @close="cleanForm"
        :destroy-on-close="true"
        v-model="showTime"
        title="时间段信息"
        width="800"
        align-center
        :close-on-click-modal="false"
      >
        <div style="padding: 20px;height: 400px">
          <el-form label-position="top" label-width="100px">

            <el-tabs v-model="time">
              <el-tab-pane label="时间段" name="times">
                <el-table :data="rows" style="width: 100%;height: 270px;overflow-y: auto;">
                  <el-table-column label="开始时间">
                    <template v-slot="{ row }">
                      <el-time-picker disabled v-model="row.startTime" placeholder="选择开始时间" style="width: 100%" />
                    </template>
                  </el-table-column>
                  <el-table-column label="结束时间">
                    <template v-slot="{ row }">
                      <el-time-picker disabled v-model="row.endTime" placeholder="选择结束时间" style="width: 100%" />
                    </template>
                  </el-table-column>
                  <el-table-column label="启用状态">
                    <template v-slot="{ row }">
                      <el-switch disabled v-model="row.isAvailable" active-text="启用" inactive-text="停用" active-value="1" inactive-value="0" />
                    </template>
                  </el-table-column>
                  <el-table-column label="操作">
                    <template v-slot="{ row, $index }">
                      <el-button disabled type="danger" circle plain :icon="Delete" @click="deleteRow($index)"></el-button>
                    </template>
                  </el-table-column>
                </el-table>

              </el-tab-pane>

            </el-tabs>

          </el-form>
        </div>


      </el-dialog>


    </div>
  </div>


</template>

<script lang="ts" setup>
import {getRoom, addRoom, updateRoom, deleteRoom, deleteAll} from '@/api/room.js'
import {addTimeslot, checkTime, getTimeslotById, updateTimeslot} from '@/api/timeslot.js'
import {Delete, Edit} from "@element-plus/icons-vue";
import {onMounted, reactive, ref} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";

onMounted(()=>{
  getRoomList()
})

const backText=((row)=>{
  if (row.timetotal!==null&&row.timetotal!==0){
    return row.timetotal+' 段';
  }else {
    return '暂无';
  }
})

const tableData=ref([])
const getRoomList=(async ()=>{
  let res=await getRoom()
  console.log(res)
  if (res.code===200){
    tableData.value=res.data
  }
})

const showRoom = ref(false)
const roomClass=ref('room')
const dialogTitle=ref('')

//表单数据
const roomForm=ref({
  room:'',
  capacity:'',
  location:'',
})

const sou=ref(false)
const saveRoom=(async ()=>{
  if (roomForm.value.room&&roomForm.value.location){
    let res=await addRoom(roomForm.value)
    console.log(res)
    if (res.code===200){
      if (rows.value.length!==0){
        //执行添加时间段操作
        console.log(rows.value)
        const list=rows.value
        //新增时间数据并插入id res.data
        list.forEach(item => {
          item.consultationRoomId = Number(res.data)
        })
        console.log(rows.value)
        let timeRes=await addTimeslot(list)
        if (timeRes.code===200){
          ElMessage.success(timeRes.message)
          showRoom.value=false
          //刷新表格
          await getRoomList()
          //清空表单
          cleanForm()
          roomClass.value='room'
        }else {
          ElMessage.warning(timeRes.errMsg)
        }
      }else {
        ElMessage.success(res.message)
        showRoom.value=false
        //刷新表格
        await getRoomList()
        //清空表单
        cleanForm()
        roomClass.value='room'
      }

    }


  }else {
    ElMessage.warning("请填写完整")
  }
})

//清空表单
const cleanForm=(()=>{
  roomForm.value={
    room:'',
    capacity:'',
    location:'',
  }
  rows.value=[]
  roomClass.value='room'
})

const rows = ref([
]);

const addRow = () => {
  rows.value.push({
    startTime: '',
    endTime: '',
    isAvailable: '1'
  });
};

const deleteRow = (index: number) => {
  rows.value.splice(index, 1);
};





const roomId=ref(0)
const update=(async (row)=>{
  roomClass.value='room'
  roomForm.value=row
  roomId.value=row.consultationRoomId
  //查询当前时间段并且渲染
  let res=await getTimeslotById(row.consultationRoomId)
  console.log(res)
  if (res.code===200){
    let list=res.data
    list.forEach(item=>{
      item.isAvailable=item.isAvailable.toString()
    })
    rows.value=list
  }
})


const saveOrUpdate=(async ()=>{
  if (!sou.value){
    //新增
    await saveRoom()
  }else {
    //修改
    //修改咨询室
    let res=await updateRoom(roomForm.value)
    if (res.code===200){
      console.log("修改了咨询室")
      //修改咨询室中的时间段
      if (rows.value.length!==0){
        console.log("修改了时间段")
        console.log(rows.value)
        let list=rows.value
        list.forEach(item=>{
          item.consultationRoomId=roomId.value
        })
        let body={
          list:rows.value,
          consultationRoomId:roomId.value
        }
        let timeRes=await updateTimeslot(body)
        if (timeRes.code===200){
          ElMessage.success("修改成功")
          await getRoomList()
          showRoom.value=false
          cleanForm()
          roomClass.value='room'
        }else {
          ElMessage.warning(timeRes.errMsg)
        }
      }else {
        //删除所有时间段然后置0
        let res=await checkTime({id:roomId.value})
        if (res.code===200){
          ElMessage.success("修改成功")
          await getRoomList()
          showRoom.value=false
          cleanForm()
          roomClass.value='room'
        }else {
          ElMessage.warning(res.errMsg)
        }

      }

    }else {
      ElMessage.warning(res.errMsg)
    }


  }
})






const showConfirmDialog = (row) => {
  ElMessageBox.confirm(
    '您确定要删除吗？',
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    if (row.timetotal){
      ElMessage.warning("存在预设时间段")
    }else {
      deleteItem(row);
    }
    // 执行删除操作

  }).catch(() => {

  });
};

//单个删除
const deleteItem = async (row) => {

  let res=await deleteRoom(row)
  if (res.code===200){
    ElMessage.success("删除成功")
    await getRoomList()
  }else {
    ElMessage.warning(res.errMsg)
  }


};
//批量删除
const selected=ref([])
function selectRoom(selectedRows) {
  console.log(selectedRows)
  selected.value=selectedRows
}

const delAll=(async ()=>{
  if (selected.value.length==0){
    ElMessage.warning("请先选择数据")
  }else {
    await ElMessageBox.confirm(
      '您确定要删除吗？',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(() => {

      // 执行删除操作
      dels()

    }).catch((err) => {
      console.log(err)
    });
  }

})
const dels=(async ()=>{
  let res=await deleteAll(selected.value)
  if (res.code===200){
    ElMessage.success("删除成功")
    await getRoomList()
  }else {
    ElMessage.warning(res.errMsg)
  }
})




//展示时间详情信息
const time=ref('times')
const showTime=ref(false)
const showTimes=(async (row)=>{
  //查询当前时间段并且渲染
  let res=await getTimeslotById(row.consultationRoomId)
  console.log(res)
  if (res.code===200){
    let list=res.data
    list.forEach(item=>{
      item.isAvailable=item.isAvailable.toString()
    })
    rows.value=list
  }

  showTime.value=true
})

</script>

<style>

</style>
